package xyz.xpman.prisonerfitness.util;

import android.content.Context;
import android.content.res.AssetManager;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@SuppressWarnings("unused")
public class AssetsUtil {

    private AssetsUtil() {}



    /**
     * 将asset里面的文件复制到
     * /data/user/0/报名/files 中
     * @param context context
     * @param assertName dirName
     */
    public static void loadAssetsToCache(@NotNull Context context, String assertName){
        final AssetManager assetManager = context.getAssets();
        final String filePath = context.getFilesDir().getAbsolutePath();
        final String targetFileName = filePath + "/" + assertName;
        FileUtil.createFile(new File(targetFileName));


        try (InputStream inputStream = assetManager.open(assertName);
             FileOutputStream outputStream = new FileOutputStream(targetFileName)) {

            int count;
            byte[] buffer = new byte[1024];

            while ((count = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void copyAssertDirToData(@NotNull Context context,
                                     @NotNull String originAssetDir,
                                     @NotNull String targetDir) {
        String[] files;
        try {
            files = context.getResources().getAssets().list(originAssetDir);
        } catch (IOException e1) {
            return;
        }

        FileUtil.mkdirs(new File(targetDir));


        for (String fileName : files) {
            // 为文件夹啊
            if (!fileName.contains(".")) {
                if (0 == originAssetDir.length()) {
                    copyAssertDirToData(context, fileName, targetDir + fileName + "/");
                } else {
                    copyAssertDirToData(context, originAssetDir + "/" + fileName, targetDir + "/" + fileName);
                }
                continue;
            }


            String originFileName = fileName;

            if (0 != originAssetDir.length()) {
                originFileName = originAssetDir + "/" + fileName;
            }

            File outFile = new File(new File(targetDir), fileName);
            FileUtil.deleteIfExists(outFile);

            try (InputStream in = context.getAssets().open(originFileName);
                 OutputStream out = new FileOutputStream(outFile)) {

                StreamUtils.write(in, out);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
